import { IQueryData, IState, IUserAnswer, MODELS, SUBJECTS } from '../typings';
import { TAction } from './actions';
import initialState from './state';
import * as types from './actionTypes';

function reducers(state: IState = initialState, action: TAction): IState {
  switch (action.type) {
    case types.SET_STATE_DEFAULT:
      //reducer 最终是要返回一个state
      //如果要改变state中某个属性
      //先把state扩展到一个新的对象中然后再修改需要的属性
      return {
        //此展开state写法是为了返回一个新的state引用
        ...state,
        queryList: [],
        userAnswers: [],
        curSubject: SUBJECTS.s1,
        curModel: MODELS.c1,
        modelShow: true,
        total: 5
      } as IState;
    case types.SET_CURRENT_SUBJECT:
      return {
        ...state,
        //后端接口业务需求 当subject=4时可省略 即选了科目4时隐藏驾照类型
        modelShow: action.payload === SUBJECTS.s4 ? false : true,
        curSubject: action.payload as SUBJECTS
      } as IState;
    case types.SET_CURRENT_MODEL:
      return {
        ...state,
        curModel: action.payload as MODELS
      } as IState;
    case types.SET_QUERY_LIST:
      return {
        ...state,
        queryList: action.payload as IQueryData[]
      } as IState;
    case types.SET_USER_ANSWER:
      const userAnswers: IUserAnswer[] = [
        ...state.userAnswers,
        action.payload as IUserAnswer
      ];
      return {
        ...state,
        userAnswers
      } as IState;
    default:
      return state;
  }
}

export default reducers;
